package com.ruibang.glass.portal.service;

import com.alibaba.fastjson.JSON;
import com.ruibang.glass.portal.domain.GlobalUser;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.BindException;
import java.util.Optional;

@Service
public class CommonService {

//    @Autowired
//    private RedisSingleService redisService;

    @Autowired
    private RedisSingleService redisService;

    /**
     * 获取userId
     *
     * @return
     */
    public GlobalUser getUser() throws BindException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Object token = request.getHeader("token");
        if (token == null) {
            token = request.getAttribute("token");
        }
        if (Optional.ofNullable(token).isPresent()) {
            if (redisService.hasKey(token.toString())) {
                String json = redisService.get(token.toString()).toString();
                if (StringUtils.isNotBlank(json)) {
                    return JSON.parseObject(json, GlobalUser.class);
                }
            }
        } else {
            throw new BindException("用户登录失效，请重新登录");
        }
        return null;
    }
}
